package org.tinygroup.uiml.fileprocessor;

import org.tinygroup.fileresolver.impl.AbstractFileProcessor;
import org.tinygroup.logger.LogLevel;
import org.tinygroup.uiml.UimlEngine;
import org.tinygroup.uiml.metadata.ComponentType;
import org.tinygroup.vfs.FileObject;
import org.tinygroup.xstream.XStreamFactory;

import com.thoughtworks.xstream.XStream;

public class UimlComponentTypeFileProcessor extends AbstractFileProcessor {
	
	private static final String COMPONENT_TYPE_EXT_FILENAME = ".componenttype.xml";

	private UimlEngine uimlEngine;
	
	
	public UimlEngine getUimlEngine() {
		return uimlEngine;
	}


	public void setUimlEngine(UimlEngine uimlEngine) {
		this.uimlEngine = uimlEngine;
	}

	public boolean checkMatch(FileObject fileObject) {
		return fileObject.getFileName().endsWith(COMPONENT_TYPE_EXT_FILENAME);
	}

	public void process() {

		XStream stream = XStreamFactory
				.getXStream(UimlEngine.XSTREAM_PACKAGENAME);
		for (FileObject fileObject : deleteList) {
			LOGGER.logMessage(LogLevel.INFO, "正在删除uiml组件类型配置文件[{0}]",
					fileObject.getAbsolutePath());
			ComponentType componentType = (ComponentType) caches.get(fileObject.getAbsolutePath());
			if (componentType != null) {
				uimlEngine.removeComponentType(componentType);
				caches.remove(fileObject.getAbsolutePath());
			}
			LOGGER.logMessage(LogLevel.INFO, "删除uiml组件类型配置文件[{0}]结束",
					fileObject.getAbsolutePath());
		}
		for (FileObject fileObject : changeList) {
			LOGGER.logMessage(LogLevel.INFO, "正在读取uiml组件类型配置文件[{0}]",
					fileObject.getAbsolutePath());
			ComponentType oldComponentType=(ComponentType)caches.get(fileObject.getAbsolutePath());
			if(oldComponentType!=null){
				uimlEngine.removeComponentType(oldComponentType);
			}
			ComponentType componentType=(ComponentType)stream.fromXML(fileObject.getInputStream());
			uimlEngine.addComponentType(componentType);
            caches.put(fileObject.getAbsolutePath(), componentType);
			LOGGER.logMessage(LogLevel.INFO, "读取uiml组件类型配置文件[{0}]结束",
					fileObject.getAbsolutePath());
		}
		
	}

}
